package com.lxs.demo.controller;

import com.github.pagehelper.PageInfo;
import com.lxs.demo.entity.Bill;
import com.lxs.demo.entity.BillType;
import com.lxs.demo.service.IBillService;
import com.lxs.demo.service.IBillTypeService;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lxs
 * @since 2024-04-29
 */
@Controller
@RequestMapping("/bill")
public class BillController {
    @Resource
    private IBillService billService;

    @Resource
    private IBillTypeService typeService;

    /**
     * 分页查询
     * @param bill
     * @param pageNum
     * @param pageSize
     * @param model
     * @return
     */
    @RequestMapping("/list-page")
    public String listPage(Bill bill,
                           @RequestParam(defaultValue = "1") int pageNum,
                           @RequestParam(defaultValue = "10") int pageSize,
                           Model model) {
        PageInfo<Bill> page = billService.listPage(bill, pageNum, pageSize);
        model.addAttribute("page", page);

        List<BillType> list = typeService.list();
        model.addAttribute("types", list);

        model.addAttribute("bill", bill);
        return "/bill/list-page";
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable("id") Integer id) {
        billService.removeById(id);
        return "redirect:/bill/list-page";
    }

    @RequestMapping("/delete")
    public String delete(Integer[] ids) {
//        billService.removeBatchByIds(Arrays.stream(ids).collect(Collectors.toList()));
        billService.removeBatchByIds(Arrays.asList(ids));
        return "redirect:/bill/list-page";
    }

    @RequestMapping("/toAdd")
    public String toAdd(Model model) {
        List<BillType> list = typeService.list();
        model.addAttribute("types", list);
        return "/bill/add";
    }

    @RequestMapping("/add")
    public String add(Bill bill) {
        billService.save(bill);
        return "redirect:/bill/list-page";
    }

    @RequestMapping("/toUpdate")
    public String toUpdate(Integer id, Model model) {
        List<BillType> list = typeService.list();
        model.addAttribute("types", list);

        Bill bill = billService.getById(id);
        model.addAttribute("bill", bill);

        return "/bill/update";
    }

    @RequestMapping("/update")
    public String update(Bill bill) {
        billService.updateById(bill);
        return "redirect:/bill/list-page";
    }


}
